<template>
  <ul class="cg-pagination" ref="pagination">
    <li class="prev" @click="change(currentPage - 1)">
      <svg-icon icon-name="left" :icon-color="'#333333'" />
    </li>
    <li
      :class="['number', { active: currentPage === index }]"
      v-for="index in pagers"
      :key="index"
      @click="change(index)"
    >
      {{ index }}
    </li>
    <li class="next" @click="change(currentPage + 1)">
      <svg-icon icon-name="right" :icon-color="'#333333'" />
    </li>
  </ul>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { limitValue } from '../../tools/index'

// 定义组件名称
defineOptions({
  name: 'cg-pagination'
})

// 定义props
const props = withDefaults(
  defineProps<{
    currentPage: number
    pageSize: number
    total: number
    disabled?: boolean
  }>(),
  {
    disabled: false
  }
)

// 定义emits
const emit = defineEmits<{
  (e: 'current-change', value: number): void
}>()

// 计算属性
const max = computed(() => {
  const { pageSize, total } = props
  return Math.ceil(total / pageSize)
})

const pagers = computed(() => {
  return Array.from({ length: max.value }).map((v, i) => i + 1)
})

// 方法
const change = (number: number) => {
  console.log('change', number)
  emit('current-change', limitValue(number, 1, max.value))
}
</script>

<style lang="scss">
.cg-pagination {
  user-select: none;
  list-style: none;
  display: inline-block;
  vertical-align: top;
  font-size: 1rem;
  padding: 1rem 0;
  margin: 0;

  li {
    background: #fff;
    vertical-align: top;
    display: inline-block;
    font-size: 1em;
    min-width: 2em;
    height: 2em;
    line-height: 2em;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    margin: 0;
  }

  li + li {
    margin-left: 0.5em;
  }

  .number {
    &.active {
      color: #4a90e5;
      background-color: #edf4fc;
    }
  }
}
</style>
